package com.android.geotrack.user;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import com.android.geotrack.GeoActivity;
import com.android.geotrack.R;
import com.android.geotrack.TrackActivity;
import com.android.geotrack.R.drawable;
import com.android.geotrack.R.string;


import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Message;
import android.util.Log;

public class LoadUsersRunnable implements Runnable
{
	private User currentUser;
	private Activity caller;
	public volatile static boolean lur_started = false;
	
	public LoadUsersRunnable(User currentUser, Activity caller)
	{
		this.currentUser = currentUser;
		this.caller = caller;
	}
	
	public void run()
	{
		this.lur_started = true;
		
		List<User> users = new LinkedList<User>();
		
		/* Start parsing. */
		try {
			Log.v("LoadUsersRunnable", "Started parsing.");
			
			// Make URL.
			URL url = new URL("http://" 
					+ caller.getResources().getString(R.string.host) 
					+ "/geo_users.php?user=" 
					+ currentUser.getName() + "&lat=" 
					+ currentUser.getLatitude() + "&lon=" 
					+ currentUser.getLongitude());
			
	        // Get a SAXParser from the SAXPArserFactory.
	        SAXParserFactory spf = SAXParserFactory.newInstance();
	        SAXParser sp = spf.newSAXParser();

	        // Get the XMLReader of the SAXParser we created.
	        XMLReader xr = sp.getXMLReader();
	        // Create a new ContentHandler and apply it to the XML-Reader.
	        UserParser parser = new UserParser();
	        xr.setContentHandler(parser);
	        
	        // Parse the xml-data from our URL.
			Log.v("Connecting...", url.toString());
	        xr.parse(new InputSource(url.openStream()));
			
			Log.v("LoadUsersRunnable", "Parsing finished.");
	        
	        /* Parsing has finished. */
	        
	        users = parser.getParseResult();

		} catch (ParserConfigurationException e) {
			Log.e("ParserConfigurationException", e.toString());
		} catch (SAXException e) {
			Log.e("SAXException", e.toString());
		} catch (IOException e) {
			Log.e("IOException", e.toString());
		}
		
		// check what to return (yes, we know, we know, not the best approach...)
		if(caller instanceof GeoActivity) {
			
			// Send results
			Message msg = ((GeoActivity)caller).messageHandler.obtainMessage();
			msg.what = 1337;
			msg.obj = users;
			((GeoActivity)caller).messageHandler.sendMessage(msg);
			
		} else if (caller instanceof TrackActivity) {
			
			// Draw thumbnails
			LinkedList<Drawable> thumbs = new LinkedList<Drawable>();
			for ( User u : users ) {
				String image = u.getThumbnail_medium();
				if (image!=null && ! image.equals("")) {
					try {
						thumbs.add(Drawable.createFromStream(new URL(image).openStream(), ""));
					} catch (MalformedURLException e) {
						Log.e("MalformedURLException", e.toString());
					} catch (IOException e) {
						Log.e("IOException", e.toString());
					}
				} else {
					thumbs.add(caller.getResources().getDrawable(R.drawable.user));
				}
			}
			
			// Send results
			Message msg = ((TrackActivity)caller).messageHandler.obtainMessage();
			msg.what = 1337;
			Object [] results = new Object[2];
			results[0] = users;
			results[1] = thumbs;
			msg.obj = results;
			((TrackActivity)caller).messageHandler.sendMessage(msg);
			
		}
		
		this.lur_started = false;
	}

}